#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <pthread.h>
#include <string.h>

#define START	100
#define END		300
#define N		4

// 统计个数的
static int cnt;
static pthread_mutex_t cnt_mut = PTHREAD_MUTEX_INITIALIZER;

static int job;
/*
 job == 0	新的任务未发放
 job > 0	发放的任务，还未取走
 job == -1	所有的任务发放完成
 */
// 存取job就是临界区
static pthread_mutex_t mut = PTHREAD_MUTEX_INITIALIZER;

static int is_primer(int n);
static void *thr_job(void *s);

int main(void)
{
	pthread_t tid[N] = {};
	int i, err;

	for (i = 0; i < N; i++) {
		err = pthread_create(tid + i, NULL, thr_job, NULL);
		if (err) {
			fprintf(stderr, "pthread_create():%s\n", strerror(err));
			exit(1);
		}
	}

	// 发放任务
	for (i = START; i <= END; i++) {
		// 竞争互斥量
		pthread_mutex_lock(&mut);
		while (job > 0) {
			// 上一次发放的任务还没有领走
			pthread_mutex_unlock(&mut);
			pthread_mutex_lock(&mut);
		}
		job = i;
		pthread_mutex_unlock(&mut);
		sleep(1);
	}

	pthread_mutex_lock(&mut);
	while (job > 0) {
		// 最后一个任务还没有取走
		pthread_mutex_unlock(&mut);
		pthread_mutex_lock(&mut);
	}
	job = -1;	
	pthread_mutex_unlock(&mut);

	for (i = 0; i < N; i++)
		pthread_join(tid[i], NULL);

	printf("共有%d个质数\n", cnt);

	pthread_mutex_destroy(&mut);
	pthread_mutex_destroy(&cnt_mut);

	return 0;
}

static void *thr_job(void *s)
{
	int value;

	while (1) {
		pthread_mutex_lock(&mut);	
		while (job == 0) {
			pthread_mutex_unlock(&mut);
			pthread_mutex_lock(&mut);
		}
		if (job == -1) {
			pthread_mutex_unlock(&mut);
			break;
		}
		value = job;
		job = 0;
		pthread_mutex_unlock(&mut);
		if (is_primer(value)) {
			printf("%d is a primer\n", value);
			pthread_mutex_lock(&cnt_mut);
			cnt++;
			pthread_mutex_unlock(&cnt_mut);
		}
	}

	return (void *)0;
}

static int is_primer(int n)
{
	int i;	

	for (i = 2; i <= n / 2; i++) {
		if (n % i == 0)
			return 0;
	}

	return 1;
}

